package com.tdwyz.fictionmanage.interceptor;

import com.tdwyz.fictionmanage.utils.JwtUtil;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author 14543
 * @version 1.0
 * @description: TODO
 * @date 2024/7/17 15:03
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate template;

    /**
     * 前置处理
     * Controller方法处理之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //过滤options
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        String token = request.getHeader("token");

        if (token == null) {//token不能为空
            response.setStatus(401);
            return false;
        }

        try {
            //检验redis中是否存在
            ValueOperations<String, String> operations = template.opsForValue();
            //从redis中取出token
            String redisToken = operations.get(token);
            if (redisToken==null) {//token不存在
                response.setStatus(401);
                return false;
            }
            //token存在，解析token
            Map<String, Object> map = JwtUtil.parseToken(token);

            //将token存入本地的线程
            ThreadLocalUtil.set(map);
        } catch (Exception e) {//拦截redis挂断而导致的报错，返回我们的报错信息
            response.setStatus(401);
            return false;
        }

        //放行请求
        return true;
    }

    /**
     * Controller方法处理完之后，DispatcherServlet进行视图的渲染之前，也就是说在这个方法中你可以对ModelAndView进行操作。
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * DispatcherServlet进行视图的渲染之后
     * 多用于清理资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal数据
        ThreadLocalUtil.remove();
    }
}
